#include	"NameFilter.h"
#include	"TextFilter.h"

#include	<Logger.h>
#include	<algorithm>
#include	<cstdio>
#include	<cstring>

#if defined(_WIN32)
#	pragma	warning(disable:4996)
#endif

bool NameFilter::Initialize() {
	char buffer[512] = { 0 };
	FILE * file = NULL;

	if ((file = fopen("settings/filter/namecharacter.txt", "r")) == NULL) {
		LOG_ERR("Failed to open settings/filter/namecharacter.txt");
		return false;
	}

	while (!feof(file)) {
		memset(buffer, 0, 512);

		char * p = fgets(buffer, 512, file);
		if (!p) break;

		while (*p && *p != '\r' && *p != '\n') {
			size_t n = 0;
			uint32_t c = TextFilter::Instance().Char(p, n);
			if (!c) break;
			_characters.push_back(c);
			p += n;
		}
	}

	std::sort(_characters.begin(), _characters.end(), [](uint32_t l, uint32_t r) { return l < r; });
	return true;
}

bool NameFilter::Check(const std::string & name) {
	if (name.empty()) return false;

	char * p = (char *)name.c_str();
	size_t n = name.size();

	for (size_t i = 0; i < n; ) {
		size_t l = 0;
		uint32_t c = TextFilter::Instance().Char(p + i, l);

		if (c == 0 || !std::binary_search(_characters.begin(), _characters.end(), c))
			return false;
		else
			i += l;
	}

	return TextFilter::Instance().Check(name);
}